package demo.engine.template;

import demo.api.ding.DingSendUtils;
import demo.engine.template.image.CssBoxDemo;
import demo.java.io.IoDemo;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.fit.cssbox.demo.ImageRenderer;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.xhtmlrenderer.util.FSImageWriter;
import org.xml.sax.SAXException;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class MarkdownDemo {

    private static String parseMarkdownToHtml(String markdownContent) {
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdownContent);
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        return renderer.render(document);
    }

    /**
     * 生成HTML文件
     *
     * @param markdownContent
     * @param htmlFilePath
     * @throws IOException
     */
    public static void markdown2HtmlFile(String markdownContent, String htmlFilePath) throws IOException {
        String htmlContent = parseMarkdownToHtml(markdownContent);
        IoDemo.writeFile(htmlFilePath, htmlContent, StandardCharsets.UTF_8);
    }

    private static void saveImageToFile(BufferedImage image, String filePath) throws IOException {
        File file = new File(filePath);
        try (OutputStream os = Files.newOutputStream(file.toPath());) {
            FSImageWriter imageWriter = new FSImageWriter();
            imageWriter.write(image, os);
        }
    }

    private static void renderHtmlToImage(String htmlContent, String outputImagePath) {
//        System.setProperty("webdriver.chrome.driver", "path_to_chromedriver"); // Specify the path to your chromedriver executable

        WebDriver driver = new ChromeDriver();

        // Load HTML content in a browser
        driver.get("data:text/html," + htmlContent);

        // Find the HTML element
        WebElement element = driver.findElement(By.tagName("body"));

        // Take a screenshot of the element
        File image = element.getScreenshotAs(OutputType.FILE);

        // Save the screenshot as an image file
//            ImageIO.write(image, "png", new File(outputImagePath));
        System.out.println("Image saved to: " + image);

        // Close the browser
        driver.quit();
    }

//    private static BufferedImage renderHtmlToImage(String htmlContent) {
//        Document doc = Jsoup.parse(htmlContent);
//        doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
//        doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
//
//        Java2DRenderer renderer = new Java2DRenderer(doc, 800);
//        return renderer.getImage();
//    }

    /**
     * markdown 链接
     *
     * @param text
     * @param linkUrl
     * @return
     */
    public static String mdLink(String text, String linkUrl) {
        return String.format("[%s](%s)", text, linkUrl);
    }

    /**
     * 图片链接
     *
     * @param linkUrl
     * @return
     */
    public static String mdPicture(String linkUrl) {
        return String.format("![](%s)", linkUrl);
    }

    /**
     * markdown 无序列表
     *
     * @param item
     * @return
     */
    public static String mdUnorderedList(String item) {
        return String.format("- %s%n", item);
    }

    /**
     * markdown 无序列表 - 二级
     *
     * @param item
     * @return
     * @deprecated 电脑显示正常，手机显示有问题
     */
    public static String mdSubList(String item) {
        return String.format("\t\t- %s%n", item);
    }

    /**
     * markdown 斜体
     *
     * @param
     * @return
     */
    public static String mdItalics(String text) {
        return String.format("*%s*", text);
    }

    /**
     * markdown 横线
     *
     * @param
     * @return
     */
    public static String mdLine() {
        return "\n\n---\n";
    }

    /**
     * Markdown 标题
     *
     * @param title
     * @param level
     * @return
     */
    public static String mdTitle(String title, int level) {
        switch (level) {
            case 1:
                return String.format("# %s %n", title);
            case 2:
                return String.format("## %s %n", title);
            case 3:
                return String.format("### %s %n", title);
            case 4:
                return String.format("#### %s %n", title);
            case 5:
                return String.format("##### %s %n", title);
            case 6:
            default:
                return String.format("###### %s %n", title);
        }

    }

    /**
     * markdown 输出 故障报警、风险报警、通知报警
     *
     * @return
     */
    public static String mdFontColor(String msg, FontColor color) {
        if (color == null) {
            return msg;
        }
        return String.format("<font color=%s>%s</font>", color.getRgb(), msg);
    }

    /**
     * markdown 加粗
     *
     * @param text
     * @return
     */
    public static String mdBold(String text) {
        return String.format("**%s**", text);
    }

    /**
     * markdown 表格
     *
     * @param header
     * @param data
     * @return
     */
    public static StringBuilder mdTable(String[] header, List<String[]> data) {
        StringBuilder md = new StringBuilder();
        String mdHeader = String.format("|%s|\n", String.join("|", header));
        md.append(mdHeader);
        String mdLine = "|" + Arrays.stream(header).map(s -> "---|").collect(Collectors.joining()) + "\n";
        md.append(mdLine);
        data.stream()
                .map(d -> String.format("|%s|\n", String.join("|", d)))
                .forEach(md::append);
        return md;
    }

    /**
     * markdown 表格
     *
     * @param data
     * @return
     */
    public static StringBuilder htmlTable(String[] header, List<String[]> data) {
        StringBuilder html = new StringBuilder("<table border='1' cellpadding='8'>\n");
        if (header != null && header.length > 0) {
            String th = Arrays.stream(header)
                    .map(h -> String.format("<th>%s</th>", h))
                    .collect(Collectors.joining("\n"));
            html.append(String.format("<tr>%n%s%n</tr>", th));
        }
        if (data != null && !data.isEmpty()) {
            String lines = data.stream().map(array -> {
                String td = Arrays.stream(array)
                        .map(h -> String.format("<td>%s</td>", h))
                        .collect(Collectors.joining("\n"));
                return String.format("<tr>%n%s%n</tr>", td);
            }).collect(Collectors.joining("\n"));
            html.append(lines);
        }
        html.append("\n</table>");
        return html;
    }

    /**
     * 引用
     *
     * @return
     */
    public static String mdQuote(String msg) {
        return String.format("> %s", msg);
    }

    @Test
    public void testMdTable() throws IOException, SAXException {
        String[] header = {"报警类型", "分组", "域名", "实例"};
        List<String[]> data = Arrays.asList(
                new String[]{"流量下跌", "wap", "linkeye.ximalaya.com", "10.10.10.10"},
                new String[]{"5xx报警", "xdcs", "xdcs-collector.ximalaya.com", "sh-nh-b24-302-n11-nginx-88-232"}
        );
        StringBuilder msg = mdTable(header, data);
        System.out.println(msg);

        DingSendUtils.sendMarkdownMsg("测试", msg, Collections.emptyList(), "", false);

        String htmlFilePath = "/Users/xmly/Documents/tmp/test.html";
        markdown2HtmlFile(msg.toString(), htmlFilePath);
        String imagePath = "/Users/xmly/Documents/tmp/test.png";
        ImageRenderer render = new ImageRenderer();
//        render.setWindowSize(new Dimension(800, 1000), false);

        String url = new File(htmlFilePath).toURI().toString();
        FileOutputStream out = new FileOutputStream(imagePath);
        render.renderURL(url, out);
        System.out.println("OK");
    }

    @Test
    public void testHtmlTable() throws IOException, SAXException {
        String[] header = {"报警类型", "分组", "域名", "实例"};
        List<String[]> data = Arrays.asList(
                new String[]{"流量下跌", "wap", "linkeye.ximalaya.com", "10.10.10.10"},
                new String[]{"5xx报警", "xdcs", "xdcs-collector.ximalaya.com", "sh-nh-b24-302-n11-nginx-88-232"}
        );
        StringBuilder msg = htmlTable(header, data);
        System.out.println(msg);

        DingSendUtils.sendMarkdownMsg("测试", msg, Collections.singletonList(""), "", false);

        String htmlFilePath = "/Users/xmly/Documents/tmp/test.html";
        markdown2HtmlFile(msg.toString(), htmlFilePath);
        String imagePath = "/Users/xmly/Documents/tmp/test.png";
        ImageRenderer render = new ImageRenderer();
//        render.setWindowSize(new Dimension(800, 1000), false);

        String url = new File(htmlFilePath).toURI().toString();
        FileOutputStream out = new FileOutputStream(imagePath);
        render.renderURL(url, out);
        System.out.println("OK");
    }

    @Test
    public void testMd2Image2() throws IOException, SAXException {
        // Load your Markdown content (replace with your own)
        String markdownContent = "# Hello, world!\nThis is a *Markdown* example.";
        String htmlFilePath = "/Users/xmly/Documents/tmp/test.html";
        markdown2HtmlFile(markdownContent, htmlFilePath);
        String imagePath = "/Users/xmly/Documents/tmp/test.png";
        CssBoxDemo.html2Image(htmlFilePath, imagePath);
    }

    @Test
    public void testMd2Image() {
        // Load your Markdown content (replace with your own)
        String markdownContent = "# Hello, world!\nThis is a *Markdown* example.";

        // Parse Markdown to HTML
        String htmlContent = parseMarkdownToHtml(markdownContent);
        System.out.println(htmlContent);

        // Render HTML to image
        renderHtmlToImage(htmlContent, "output.png");
    }

    public enum FontColor {
        RED("#FF0000"), ORANGE("#FF9900"), BLUE("#0066FF");

        private String rgb;

        FontColor(String rgb) {
            this.rgb = rgb;
        }

        public String getRgb() {
            return rgb;
        }
    }


}
